package com.rupertjones.globalcron.web.service;

import com.rupertjones.globalcron.domain.JobDescriptor;
import com.rupertjones.globalcron.domain.dao.JobDescriptorDAO;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.rupertjones.globalcron.web.util.JodaTimeFormatter.format;

/**
 * <p>&copy Rupert Jones 2011,2012</p>
 *
 * @author rup
 */
@Service
public class DefaultTimezoneService implements TimezoneService {

    @Autowired
    private JobDescriptorDAO jobDescriptorDAO;

    //for testing
    private DateTime now;

    @Override
    public List<String> currentTimeInCurrentlyUsedZones() {
        List<DateTimeZone> timeZones = new ArrayList<DateTimeZone>();

        for(JobDescriptor job : jobDescriptorDAO.getEnabledJobs()) {
            try {
                timeZones.add(job.getTimezoneAsObject());
            } catch (IllegalArgumentException iae) {
                //ignore
            }
        }

        List<String> results = new ArrayList<String>();

        DateTime server = getNowWith(DateTimeZone.getDefault());
        results.add(format("EEE HH:mm:ss (ZZZ)", server));

        for(DateTimeZone tz : timeZones) {
            DateTime when = getNowWith(tz);
            results.add(format("EEE HH:mm:ss (ZZZ)", when));
        }

        return results;
    }

    public void setNow(DateTime now) {
        this.now = now;
    }

    private DateTime getNowWith(DateTimeZone tz) {
        return (now == null ? new DateTime(tz) : now.withZone(tz));
    }
}
